<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Promocion extends MN_Controller {

    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper(array('url', 'form'));
        $this->load->library('ion_auth');
        $this->load->library('session');
        $this->load->model('Docente_Model');
        $this->load->model('Periodos_Model');
        $this->load->model('Pensum_Model');
        $this->load->model('Carrera_Model');
        $this->load->model('Ciclos_Model');
        $this->load->model('Expediente_Model');
        $this->load->model('Estudiante_Model');
        $this->load->library('expediente');
        session_start();
    }

    public function index() {

        if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !$this->ion_auth->is_secretary())) {
            $this->session->set_flashdata('message', 'No pertence al grupo de Docentes');
            redirect('auth/login', 'refresh');
        }
        $this->data['user'] = $this->ion_auth->get_user_username();
    }

    public function inicio() {
        if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !$this->ion_auth->is_secretary())) {
            $this->session->set_flashdata('message', 'No pertence al grupo de Docentes');
            redirect('auth/login', 'refresh');
        }
        $this->data['user'] = $this->ion_auth->get_user_username();


        $this->data['periodos'] = $this->Periodos_Model->getListado();
        //$this->data['periodos'] = $this->Periodos_Model->getPeriodoActivo();
        $this->data['carrera'] = $this->Carrera_Model->getListado();

        $ide_car = $this->uri->segment(3);
        $ide_pen = $this->uri->segment(4);
        $codigo_cic = $this->uri->segment(6);
        //$seccion = $this->uri->segment(7);
        //$paralelo = $this->uri->segment(8);
        //$this->session->unset_userdata('ses_pagodoc');


        if (!empty($ide_car) && $ide_car != -1) {
            $this->data['pensum'] = $this->Pensum_Model->getPensumCarreras($ide_car);
            $this->data['ide_car'] = $ide_car;
            //$this->data['ide_pen'] = -1;
        } else {
            $this->data['ide_car'] = -1;
        }
        if (!empty($ide_pen) && $ide_pen != -1) {
            $this->data['estudiantes'] = $this->Expediente_Model->getMatriculadosCarreraPensum($ide_car,$ide_pen);
            $this->data['ide_pen'] = $ide_pen;
        } else {
            $this->data['ide_pen'] = -1;
        }

        

        $this->_render('promocion/new');
    }

   public function presenta() {
        if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !$this->ion_auth->is_secretary())) {
            $this->session->set_flashdata('message', 'No pertence al grupo de Docentes');
            redirect('auth/login', 'refresh');
        }
        $this->data['user'] = $this->ion_auth->get_user_username();

        $this->load->model('Arrastre_Model');
        $this->load->helper('numeros');
        $cod_pers = $this->uri->segment(3);
        $ide_car= $this->uri->segment(4);
        $ide_pen=$this->uri->segment(5);
        $expediente=array();
        $estudiante=array();
        $estudiante=$this->Estudiante_Model->getDatosEstudiante($cod_pers);
        $expediente= $this->expediente->getExpediente($cod_pers,$ide_pen,$estudiante,$ide_car);
        //print_r($expediente);
        //Recorrido de arreglo para verificar el color de las celdas
        $semestres=array();
        $ide_mat='';
        $codigo_cic='';
        
        //$expediente[0]['color']=1; Proceso marcar con color las materias que se repite
        for ($i=count($expediente)-1; $i>=0 ; $i--) { 
            if(($ide_mat!=$expediente[$i]['ide_mat'])){
                
                $ide_mat=$expediente[$i]['ide_mat'];


                if(!$expediente[$i]['cond_alumno']){
                    $expediente[$i]['color']=1;

                }
                if(($codigo_cic!=$expediente[$i]['codigo_cic'])){
                    $codigo_cic=$expediente[$i]['codigo_cic'];
                    $aux=array(
                    'ide_lec'=>$expediente[$i]['ide_lec'],
                    'ide_cic'=>$expediente[$i]['ide_cic'],
                    'codigo_cic'=>$expediente[$i]['codigo_cic'],
                    'seccion'=>$expediente[$i]['seccion'],
                    'paralelo'=>$expediente[$i]['paralelo'],
                    );
                    $semestres[]=$aux;

                }

                

            }

            
        }


        $this->data['materias'] = $expediente;
        $this->data['estudiante'] = $estudiante;


        $this->data['cod_pers'] = $cod_pers;
        $this->data['ide_car'] = $ide_car;
        $this->data['ide_pen'] = $ide_pen;
        $this->data['semestres'] = $semestres;

        $_SESSION["expediente"]=$expediente;


        //print_r($semestres);


        $this->_render('promocion/previewpromo');
    }

    
    function determinarNota($total1,$total2,$total3,$suple_cal){
        $nota=0;

            if($total3>=28) {
                $nota=$total3;    

            }else{
                if($suple_cal>0){
                    if($total1>=$total2){
                        $nota=$total1+$suple_cal;
                    }else{
                        $nota=$total2+$suple_cal;
                    }
                }else{
                    $nota=$total1+$total2;

                }

            }

    return $nota;
    }
    public function imprimirExpediente() {
        //$expediente=$_SESSION["expediente"];
        //print_r($expediente);
        //$ciclo=$this->input->post('ciclos');

        //echo "este es el ciclo".$ciclo;
        $ide_lec = $this->uri->segment(3);
        $seccion=$this->uri->segment(5);
        $nom_secc=($seccion==1?"DIURNO":($seccion==2?"NOCTURNO":"FIN SEMANA"));


        $periodo=$this->Periodos_Model->getDatosPeriodo($ide_lec);
        $this->data['nom_per']=$periodo[0]["descripcion_lec"];
        $this->data['nivel']=$this->uri->segment(4);
        $this->data['seccion']=$nom_secc;
        $this->data['paralelo']=$this->uri->segment(6);


        $this->data['expediente'] = $_SESSION["expediente"];


        $html = $this->load->view('promocion/expediente', $this->data, true);
        $path = $this->dompdf_lib->createPDF($html, 'myfilename1', false,'a4','landscape');

        //$path->set_paper('a4', 'portrait');//landscape

        $this->data['path'] = $path;
        

        $this->load->view('promocion/vista',$this->data);
    }


    public function imprimirExpedienteold() {
        $expediente=$_SESSION["expediente"];
        //print_r($expediente);
        //echo "este es el ciclo".$ciclo;

        $this->load->library('cezpdf');
        $this->load->helper('pdf_helper');
        $pdf = new Cezpdf('a4','landscape');
        $pdf->ezSetMargins(30, 30, 30, 30);


        $pdf->selectFont('fonts/Times-Roman.afm');

        $pdf->ezText($ciclo);
        $pdf->ezText('<strong> skdjf</strong>');
        $pdf->ezText('');
        $titulos2 = array("1" => utf8_decode("INSTITUTO TECNOLÓGICO SUPERIOR SUDAMERICANO"));
        $db_data2[] = array("1" => "Miguel Riofrio 14-55 entre Bolivar y Sucre");
        $db_data2[] = array("1" => "Nro.RUC 1900548811");
        $pdf->ezTable($db_data2, $titulos2, '', array('shadeCol' => array(1, 1, 1), 'colGap' => 1, 'shaded' => 1, 'showLines' => 0, 'width' => 500, 'fontSize' => 10, 'cols' => array("1" => array('justification' => 'center'))));

        $col_names = array( 
                'codigo_cic'=>'CICLO',
                'nombre_mat'=>'MATERIAS',
                'total1'=>'BIM1',
                'total2'=>'BIM2',
                'suple_cal'=>'REMD',
                'nota'=>'SUMA TOTAL',
                'letra_n'=>'SUMA LETRAS',
                'creditos_mat'=>'CREDITOS',
                'asiste1_cal'=>'ASIST 1B',
                'asiste2_cal'=>'ASIST 2B',
                'asiste'=>'TOTAL ASIST',
                'cond_notas'=>'COND NOTAS',
                'cond_asiste'=>'COND ASIST',
                'docente'=>'DOCENTE');
        $db_data=array();

        foreach ($expediente as $key => $row) {
            $db_data[$key]=array( 
                'codigo_cic'=>('<strong>'.$row['codigo_cic'].'</strong>'),
                'nombre_mat'=>utf8_decode($row['nombre_mat']),
                'total1'=>$row['total1'],
                'total2'=>$row['total2'],
                'suple_cal'=>$row['suple_cal'],
                'nota'=>$row['nota'],
                'letra_n'=>$row['letra_n'],
                'creditos_mat'=>$row['creditos_mat'],
                'asiste1_cal'=>$row['asiste1_cal'],
                'asiste2_cal'=>$row['asiste2_cal'],
                'asiste'=>$row['asiste'],
                'cond_notas'=>$row['cond_notas'],
                'cond_asiste'=>$row['cond_asiste'],
                'docente'=>utf8_decode($row['docente']));
        }
        $pdf->ezTable($db_data, $col_names, '', array('shadeCol' => array(1, 1, 1),'colGap' => 1, 'shaded' => 1, 'showLines' => 1,'width' => 800, 'fontSize' => 8,'xOrientation'=>'center','cols' => array('nombre_mat' => array('justification' => 'left', 'width' => '100'))));
        $pdf->ezText('');
        $pdf->ezText('');
        $pdf->ezText('');
        $pdf->ezText('');

        $titulos4 = array("1" => utf8_decode("_________________"), "2" => utf8_decode("_________________"));

        $db_data4[] = array("1" => "Recibe", "2" => utf8_decode("Cliente"));
        $db_data4[] = array("1" => "", "2" => utf8_decode(""));

        $pdf->ezTable($db_data4, $titulos4, '', array('shadeCol' => array(1, 1, 1), 'colGap' => 2, 'shaded' => 1, 'showLines' => 0, 'width' => 500, 'fontSize' => 10, 'cols' => array("1" => array('justification' => 'center'), "2" => array('justification' => 'center'))));

        $titulos5 = array("1" => utf8_decode(""), "2" => utf8_decode(""));


        $db_data5[] = array("1" => utf8_decode("OBSERVACIÓN: Este documento no es válido para Crédito tibrutario"), "2" => utf8_decode("Retirar la factura dentro de 20 días en el departamento de contabilidad"));

        $pdf->ezTable($db_data5, $titulos5, '', array('shadeCol' => array(1, 1, 1), 'colGap' => 2, 'shaded' => 1, 'showLines' => 0, 'width' => 500, 'fontSize' => 8, 'cols' => array("1" => array('justification' => 'full'), "2" => array('justification' => 'full'))));
        prep_pdf();
        ob_end_clean();
        $pdf->ezStream();
    }
    public function imprimirPromocion() {
        $expediente=$_SESSION["expediente"];
        $this->load->model('Materia_Model');
        $listap=array();
        $ciclo=$this->input->post('ciclos');
        echo $ciclo;
        
        foreach ($expediente as $key => $row) {
            if($row['ide_cic']==$ciclo ){
                $aux=array(
                    'ide_mat'=>$row['ide_mat'],
                    'ide_cic'=>$row['ide_cic'],
                    'nombre_mat'=>$row['nombre_mat'],
                    'total1'=>$row['total1'],
                    'total2'=>$row['total2'],
                    'total3'=>$row['total3'],
                    'suple_cal'=>$row['suple_cal'],
                    'nota'=>$row['nota'],
                    'letra_n'=>$row['letra_n'],
                    'cond_alumno'=>$row['cond_alumno'],
                    'semestre'=>$row['semestre'],
                    'nombres'=>$row['nombres'],
                    'carrera'=>$row['carrera']);


                $listap[]=$aux;
            }
        }
        $ide_mat=0;
        $aux1=array();
        for ($i=count($listap)-1; $i>=0 ; $i--) { 
            if(($ide_mat!=$listap[$i]['ide_mat'])){
                
                $ide_mat=$listap[$i]['ide_mat'];
                $aux1[$i]=$listap[$i];

            }

            
        } 
        $listap=$aux1;
        $listap = $this->orderMultiDimensionalArray($listap, 'semestre', false);
        $semestre_inicio=$listap[0]['semestre'];


        $listaMalla=$this->Materia_Model->getListado($ciclo);

        $promocion=array();
        //if (in_array("verde", $colores)) {
        foreach ($listaMalla as $key => $row) {
            $existe=false;
            foreach ($listap as $key => $row1) {
                if($row['ide_mat']==$row1['ide_mat']){
                    $existe=true;
                    $promocion[]=$row1;
                }

                # code...
            }
            if(!$existe && strpos(strtolower($row['nombre_mat']), "seminario")<0){

                $aux=array(
                    'ide_mat'=>$row['ide_mat'],
                    'ide_cic'=>$row['ide_cic'],
                    'nombre_mat'=>$row['nombre_mat'],
                    'total1'=>'-',
                    'total2'=>'-',
                    'total3'=>'-',
                    'suple_cal'=>'-',
                    'nota'=>'-',
                    'letra_n'=>'-',
                    'cond_alumno'=>FALSE,
                    'semestre'=>$listap[0]['semestre'],
                    'nombres'=>'X',
                    'carrera'=>$listap[0]['carrera']);


                $promocion[]=$aux;


            }
            

           
        }
        $imprime=true;
        foreach ($promocion as $key => $row) {
            if (!$row['cond_alumno']){
                $imprime=false;
                break;
            }
            # code...
        }


            # code...
        //echo "<br>";

        //print_r ($promocion);
        $this->data['promocion'] = $promocion;
        $_SESSION["promocion"]=$promocion;
        $this->data['imprime'] = true;
        $this->data['nombre_cic']=$listaMalla[0]['nombre_cic'];
        $this->_render('promocion/promocion');

        
        

    }
    public function PrintPromo() {
        //$expediente=$_SESSION["expediente"];
        //print_r($expediente);
        $this->data['promocion'] = $_SESSION["promocion"];
        $this->data['imprime'] = FALSE;
        $this->data['observa']=$this->input->post('observa');
         $this->data['nombre_cic']=$this->input->post('nombre_cic');


        $html = $this->load->view('promocion/promocion', $this->data, true);
        $path = $this->dompdf_lib->createPDF($html, 'myfilename1', false,'a4');

        //$path->set_paper('a4', 'portrait');//landscape

        $this->data['path'] = $path;
        

        $this->load->view('promocion/vista1',$this->data);
    }

function orderMultiDimensionalArray($toOrderArray, $field, $inverse = false) {
        $position = array();
        $newRow = array();
        foreach ($toOrderArray as $key => $row) {
            $position[$key] = $row[$field];
            $newRow[$key] = $row;
        }
        if ($inverse) {
            arsort($position);
        } else {
            asort($position);
        }
        $returnArray = array();
        foreach ($position as $key => $pos) {
            $returnArray[] = $newRow[$key];
        }
        return $returnArray;
    }    


}

